import React, { Component } from "react";
import { Table, Input, Button, Popconfirm, Form ,Divider,Select,Row,Col, Modal,DatePicker} from 'antd';
import Content from "../../components/Content/Content";
import moment from "moment";

const { Item } = Form;
const EditableContext = React.createContext();
const { Option } = Select;
const InputGroup = Input.Group;
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
    visible: false
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} 不能为空.`,
              
            },
          ],
          initialValue: record[dataIndex],
        })(<Input className='InputValue' ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"

        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        fixed: 'left',
        width:90,
        editable: true,
      },      
      {
        title: '筛选菌株编号', 
        dataIndex: 'sxjj_id',
      },
      {
        title: '样品编号',
        dataIndex: 'yp_id',
      },
      {
        title: '编号类型',
        dataIndex: 'scdyp_type',
        render: (text, record) => (
          <Select defaultValue={text}
          mode="tags"
          style={{ width: "100%" }}
          onChange={(value) => this.setState({scdyp_type: value[0]})}
          tokenSeparators={[","]}
          showArrow={true}
        >
            <Option value="f_fjypid">发酵样品编号</Option>
            <Option value="lf_id">流份编号</Option>
            <Option value="ctp_id">粗提品编号</Option>
            <Option value="hhw_id">化合物编号</Option>
          </Select>
        )
      },
      {
        title: '筛选样品复筛检测值',
        dataIndex: 'sc_jcz',
      },
      {
        title: '复筛空白对照',
        dataIndex: 'sc_kbdz',
        editable: true,
      },
      {
        title: '复筛阳性对照',
        dataIndex: 'sc_yxdz',
        editable: true,
      },
      {
        title: '复筛阴性对照',
        dataIndex: 'sc_yydz',
        editable: true,
      },
      {
        title: '复筛样品活性',
        dataIndex: 'sc_yphx',
        editable: true,
      },
      {
        title: '复筛结果录入时间',
        dataIndex: 'sc_time',
        
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => (
          <span>
            <Button type="dashed" onClick={() => this.showModal(record)}>
              查看
            </Button>
            <Divider type="vertical" />
            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    ];

    this.state = {
      dataSource: [], 
      count: 1,

      scdyp_type:'', // 样品编号类型

      viewData: {},
      newData: {},
      selectedRowKeys: [],  
  
      searchParams : {},

      loading: true,
      pageNum: 1,
      pageSize: 100

    };
    
  }

  showModal = (record) => {
    this.setState({
      visible: true,
      viewData: record
    });
  };

  handleOk = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  
  handleDelete = id => {
    const dataSource = [...this.state.dataSource];
           
    // 如果是新数据尚未保存，那么可以直接删除
    if( this.state.newData.id != null ) {
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      return;
    }

    const url = global.api.secondarycreeningEntering + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.loadData(1);
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    }) 

  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const initVal = count + 661;

    if( this.state.newData.id != null ) {
      Modal.error({
        content: '数据尚未保存！',
      });
      return;
    }

    const newData = {
      id: initVal,
      sxjj_id: initVal,
      yp_id : initVal,
      // scdyp_type  : '',
      sc_jcz  : initVal,
      sc_kbdz : initVal,
      sc_yxdz  : initVal,
      sc_yydz : initVal,
      sc_yphx : initVal, 
      sc_time : moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
    };

    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
      newData: newData
    });
  };

  handleSave = (row, showAlert) => {

    let record = this.state.newData;
    record.scdyp_type = this.state.scdyp_type;

    const url = global.api.secondarycreeningEntering;
    return global.network.post(url, this.state.newData)
    .then(res => {  
      this.loadData(1);

      if( showAlert ) {
        Modal.success({
          content: '保存成功!',
        });
      }
    })
    .catch(err => {
      if( showAlert ) {
        Modal.error({
          content: '保存出错，请检查传入的参数是否已经填写！',
        });
      }
    }) 

  };


  loadData = (current = 1) => {

    this.setState({ search_loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        search_loading: false
      });
    }, 1000);
    
    let { searchParams } = this.state;

    const url = global.api.secondarycreeningEntering
    + "?scdyp_type=" + (this.state.searchParams.scdyp_type || "")
    + "&sc_time=" + (this.state.searchParams.sc_time  || "")
    + "&sxjj_id=" + (this.state.searchParams.sxjj_id || "")
    + "&yp_id=" + (this.state.searchParams.yp_id || "");

    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search:{}})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count, newData: {}})
    })
    .catch(err => {
      Modal.error({
        content: '数据加载失败！'
      })
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  render() {
    const { selectedRowKeys, dataSource, search_loading } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const hasSelected = selectedRowKeys.length > 0;

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    const formItemLayoutt = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
          <div className="filtrate">
      <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>
      
        <Item label="筛选菌株编号">
                <Input onChange={e => this.state.searchParams.sxjj_id  = e.target.value } /></Item>
        <Item label="录入时间">
                <DatePicker
                  onChange={(value, dateString) => this.state.searchParams.sc_time  = dateString}
                  style={{ width: "100%" }}
                />                
        </Item> 
        <Item label="样品编号">
                <Input style={{ width: "60%" }} onChange={e => this.state.searchParams.yp_id  = e.target.value } />
                <InputGroup compact style={{ width: "40%" }}>
                <Select
                  mode="tags"
                  style={{ width: "100%" }}
                  onChange={value => this.state.searchParams.scdyp_type  = value[0]}
                  tokenSeparators={[","]}
                  showArrow={true}
                >
                    <Option value="f_fjypid">发酵样品编号</Option>
                    <Option value="lf_id">流份编号</Option>
                    <Option value="ctp_id">粗提品编号</Option>
                    <Option value="hhw_id">化合物编号</Option>
                  </Select>
                </InputGroup>
              </Item>

      <Item wrapperCol={{ span: 6, offset: 4 }}>
        <Row guuter={16}>
          <Col span={6}>
          <Button type="primary" loading={search_loading} onClick={() => this.loadData(1)}>
              查询
            </Button>
          </Col>
         
        </Row>
      </Item>
    </Form>
      </div>
      <Modal
          title="Basic Modal"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form {...formItemLayoutt} onSubmit={this.onSubmit} colon={false}>
          <Item label="ID">
                <Input defaultValue={this.state.viewData.id } readOnly />
              </Item>
              <Item label="筛选菌株编号">
                <Input defaultValue={this.state.viewData.sxjj_id } onChange={e => this.state.viewData.sxjj_id  = e.target.value } />
              </Item>
              <Item label="样品编号">
                <Input defaultValue={this.state.viewData.yp_id } onChange={e => this.state.viewData.yp_id  = e.target.value } />
              </Item>
              <Item label="样品编号类型">
                <Input defaultValue={this.state.viewData.scdyp_type   } onChange={e => this.state.viewData.scdyp_type   = e.target.value } />
              </Item>
              <Item label="复筛检测值">
                <Input defaultValue={this.state.viewData.sc_jcz   } onChange={e => this.state.viewData.sc_jcz  = e.target.value } />
              </Item>
              <Item label="复筛空白对照">
                <Input defaultValue={this.state.viewData.sc_kbdz  } onChange={e => this.state.viewData.sc_kbdz  = e.target.value } />
              </Item>
              <Item label="复筛阳性对照">
                <Input defaultValue={this.state.viewData.sc_yxdz  } onChange={e => this.state.viewData.sc_yxdz  = e.target.value } />
              </Item>
              <Item label="复筛阴性对照">
                <Input defaultValue={this.state.viewData.sc_yydz  } onChange={e => this.state.viewData.sc_yydz  = e.target.value } />
              </Item>
              <Item label="复筛样品活性">
                <Input defaultValue={this.state.viewData.sc_yphx  } onChange={e => this.state.viewData.sc_yphx  = e.target.value } />
              </Item>
              <Item label="复筛结果录入时间">
                <Input defaultValue={this.state.viewData.sc_time  } onChange={e => this.state.viewData.sc_time   = e.target.value } />
              </Item>
              <Button type="primary" onClick={this.handleUpdate } style={{marginLeft:'300px'}}>保存</Button>
            </Form>
        </Modal>
        <Button onClick={this.handleAdd} type="primary" style={{ marginLeft:'24px' }}>
          添加
        </Button>
        <Button disabled={this.state.newData.id == null} onClick={(row) => this.handleSave(row, true)} type="primary" style={{ marginLeft:'50px' }}> 
          保存
        </Button>
        <Button disabled={this.state.selectedRowKeys.length == 0} type="primary" style={{ marginLeft:'50px', marginTop: '30px' }}> 
          批量导出
        </Button>
        <span style={{ marginLeft: 8 }}>
          {hasSelected ? `选中 ${selectedRowKeys.length} 个` : ""}
        </span>

        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
        />
      </Content>
    );
  }
} 

const ActivityScreeningPrimary = Form.create()(EditableTable);
export default ActivityScreeningPrimary;
